package com.fc.backingbeans.food;

import javax.faces.bean.ViewScoped

import org.primefaces.model.chart.PieChartModel
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import com.fc.entities.Food
import com.fc.entities.FoodGroup
import com.fc.entities.User
import com.fc.service.UserDetailsService
import com.fc.service.FoodService
import com.fc.service.exceptions.FCException
import com.fc.utils.MessageUtils

/**
 * 
 * @author Ács Ádám
 *
 */
@Component("foodTableController")
@ViewScoped
class FoodTableController implements Serializable {
	@Autowired private FoodService foodService
	@Autowired private UserDetailsService userService

	List<Food> filtered
	private List<Food> foods
	Food selected
	FoodGroup foodGroup
	User user

	boolean needRefresh
	boolean systemValuesShowed = true

	List<Food> getFoods() {
		if (foods == null || needRefresh) {
			user = userService.getCurrentUser()
			if (systemValuesShowed && foodGroup) {
				foods = foodService.findAllByGroupAndUser(foodGroup, user)
				foods +=  foodService.findAllDefaultByGroup(foodGroup)
			} else if (systemValuesShowed && !foodGroup) {
				foods = foodService.findAllByUser(user)
				foods +=  foodService.findAllDefault()
			} else if (!systemValuesShowed && foodGroup) {
				foods = foodService.findAllByGroupAndUser(foodGroup, user)
			} else {
				foods = foodService.findAllByUser(user)
			}
			filtered = foods
			needRefresh = false
		}

		return foods;
	}

	void delete(Food food) {
		try {
			foodService.delete(food)
			selected = null
		} catch (FCException fcEx) {
			MessageUtils.addError("Hiba az étel törlésekor", fcEx.getMessage())
		} catch (Exception ex) {
			MessageUtils.addError("Az étel törlése nem lehetséges", "")
		}
	}

	void update(Food food) {
		try {
			foodService.save(food)
			selected = null
		} catch (FCException fcEx) {
			MessageUtils.addError("Hiba az étel módosításakor", fcEx.getMessage())
		} catch (Exception ex) {
			MessageUtils.addError("Az étel módosítása nem lehetséges", "")
		}
	}

	void deleteSelected() {
		delete(selected)
	}

	void requestRefresh() {
		needRefresh = true
	}

	List<String> getFoodNames() {
		return foodService.findAllNames();
	}

	PieChartModel getPieModel() {
		getPieModelForFood(selected)
	}

	PieChartModel getPieModelForFood(Food food) {
		PieChartModel pieModel = new PieChartModel();
		if (food) {
			pieModel.set("Fehérje", food.protein);
			pieModel.set("Szénhidrát", food.carbohydrate);
			pieModel.set("Zsír", food.fat);
			pieModel.set("Rost", food.fiber);
		}
		return pieModel
	}

	String getRowStyleClass(Food food) {
		if (food.protein > food.carbohydrate) {
			"proteinrich"
		}
		if (food.carbohydrate > food.protein) {
			"carbohydraterich"
		}
	}
}
